<template>
  <div class="root flex-col">
    <div class="image">
      <el-upload
      accept="image/*"
      v-model:file-list="fileList"
      :action="uploadUrl"
      :limit="1"
      :on-success="handleSuccess"><el-button type="primary" @click="handleClick">添加图片</el-button></el-upload>
    </div>
    <ImageList :imgList="imgList" @-picture-card-preview="handlePictureCardPreview" @remove-picture="handleRemove"/>
  </div>
  
  <!-- <el-upload
    v-model:file-list="fileList"
    :action="uploadUrl"
    list-type="picture-card"
    :on-preview="handlePictureCardPreview"
    :on-remove="handleRemove"
    :on-success="handleSuccess"
  >
    <el-icon><Plus /></el-icon>
  </el-upload> -->
  <el-dialog v-model="dialogVisible">
    <img w-full :src="dialogImageUrl" alt="Preview Image" class="pre-view"/>
  </el-dialog>
</template>
<script lang="ts">
import Global from '@/Global';
import { UploadProps, UploadUserFile } from 'element-plus';
import { defineComponent,onMounted,ref } from 'vue';
import ApiHelper from '@/api/ApiHelper';

export default defineComponent({
  name: 'ImageView',
  setup(props, ctx) {
    const baseUrl=process.env.VUE_APP_BASE_API
    const imgList=ref([])
    const fileList = ref<UploadUserFile[]>([])
    const uploadUrl=ref(Global.getInstance().baseUrl+'/upload_image')
    const handleClick = () => {
      //ctx.emit('click', '123')
    }
    const handleSuccess = (res: any) => {
      console.log(res)
      fileList.value.length=0
      getData();
    }
    const dialogImageUrl = ref('')
    const dialogVisible = ref(false)

    const handleRemove = (item) => {
      ApiHelper.getInstance().deleteImage(item.id!).then(res=>{
        console.log(res)
        getData();
      }).catch(err=>{
        console.log(err)
      })
      //getData();
    }

    const handlePictureCardPreview = (item) => {
      dialogImageUrl.value = baseUrl+item.path!
      dialogVisible.value = true
    }
    const getData=()=>{
      ApiHelper.getInstance().getImages().then(res=>{
        //console.log(res)
        /*imgList.value.length=0
        res.forEach((item:any)=>{
          imgList.value.push(item)
        })*/
        imgList.value=res
      }).catch(err=>{
        console.log(err)
      })
    }
    onMounted(()=>{
      //const str='#/login?redirect=' + encodeURIComponent(location.href)
      //console.log(str)
      getData();
    })
    return {
      handleClick,
      uploadUrl,
      fileList,
      handleSuccess,
      handlePictureCardPreview,
      handleRemove,
      dialogVisible,
      dialogImageUrl,
      imgList
    }
  }
})
</script>
<style lang="less" scoped>
.root{
  width: 100%;
  height: 100%;
  padding: 20px;
}
.pre-view{
  max-width: 100%;
}
</style>